const moment = require('moment')
const conn = require('../db/db.js')

const showRegisterPage = (req,res)=> {
    res.render('./user/register.ejs',{})
}

const showLoginPage = (req,res) => {
    res.render('./user/login.ejs',{})
}

const reg = (req,res) => {
    const body = req.body
    // 判断用户输入的数据是否完整
    // console.log(body);
    // if(body.username.trim().length<=0 || body.password.trim().length<=0 || body.nikename.trim().length<=0){
    //     return res.send({msg:'请输入正确的注册信息',ststus:'501'})
    // }
    // 查询用户名是否重复
    const sql1 = 'select count(*) as count from heima where username=?'
    conn.query(sql1,body.username,(err,result) =>{
        if(err) return res.send({msg:'用户名查询失败',status:'502'})
        if(result[0].count != 0) return res.send({msg:用户注册失败,status:'501'})        
    })
    body.ctime = moment().format('YYYY-MM-DD HH:mm:ss')
    const sql2 = 'insert into heima set ?'
    conn.query(sql2,body,(err,result)=> {
        if (err) return res.send({ msg: '注册新用户失败！', status: 504 })
        // console.log(result);
        if(result.affectedRows !=1) return res.send({msg:'新用户注册失败',status:505})
        res.send({msg:'注册成功',status:200})
    })
}

const login = (req,res) => {
    const body = req.body
    const sql3 = 'select * from heima where username =? and password = ?'
    conn.query(sql3,[body.username,body.password],(err,result) => {
        if(err) return res.send({msg:'登录失败1',status:'501'})
        // console.log(result);
        if(result.length != 1) return res.send({msg:'登录失败2',status:'502'})
        req.session.user = result[0]
        req.session.islogin = true 
        res.send({msg:'登陆成功',status:200}) 
    })
}

const logout = (req,res)=>{
    req.session.destroy(function(){
        res.redirect('/')
    })
}

module.exports = {
    showRegisterPage,
    showLoginPage,
    reg,
    login,
    logout
}